package com.seu.data.structures.binarySearchTree.d.postorder;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/
// Non-Recursive
// Using two stacks
//
// Time Complexity: O(n)
// Space Complexity: O(n)

/**
 * 非递归实现二叉树的后序遍历
 *
 * @author liangfeihu
 * @since 2018/12/4 11:42
 */
public class Solution2 {

    public List<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }

        Stack<TreeNode> stack = new Stack<>();
        Stack<Integer> output = new Stack<>();

        stack.push(root);
        while (!stack.empty()) {
            TreeNode cur = stack.pop();
            output.push(cur.val);

            if (cur.left != null) {
                stack.push(cur.left);
            }
            if (cur.right != null) {
                stack.push(cur.right);
            }
        }

        while (!output.empty()) {
            res.add(output.pop());
        }

        return res;
    }
}
